import * as fs from 'fs'
import i18n from '@/i18n'
import { SWAGGER_UI_DIR } from '@apps/server/config/app-const'
import { INestApplication } from '@nestjs/common'
import { OpenAPIObject, SwaggerModule } from '@nestjs/swagger'
import { AppLogger } from '../logger/app-logger'
import { closetTarget } from '../os'

export type SwaggerSetupFn = (app: INestApplication) => void

export class SwaggerFactory {
  protected static swaggerSetups: SwaggerSetupFn[] = []

  /**
   * 注册
   * @param setup
   * @returns
   */
  static registry(setup: SwaggerSetupFn) {
    this.swaggerSetups.push(setup)
    return this
  }

  /**
   * 配置
   * @param app
   */
  static setup(app: INestApplication) {
    this.swaggerSetups.forEach(setup => setup(app))
  }

  /**
   * 兼容非开发环境下的swagger，通过读取json文件生成swagger
   * @param app
   * @param finalPath
   * @param jsonFileName
   * @param document
   * @returns
   */
  static load(app: INestApplication, finalPath: string, jsonFileName: string, document: OpenAPIObject) {
    if (process.env.NODE_ENV === 'development') {
      SwaggerModule.setup(finalPath, app, document)
    } else {
      const customSwaggerUiPath = closetTarget(__dirname, {
        target: SWAGGER_UI_DIR,
      })
      if (!customSwaggerUiPath) {
        AppLogger.info('SwaggerConfig', i18n.t('lhy-common.swagger.index.12154285-0'))
        return
      }

      const jsonFilePath = closetTarget(__dirname, {
        target: jsonFileName,
      })
      if (!jsonFilePath) {
        AppLogger.info('SwaggerConfig', i18n.t('lhy-common.swagger.index.12154285-1', { args: [jsonFileName] }))
        return
      }

      SwaggerModule.setup(finalPath, app, JSON.parse(fs.readFileSync(jsonFilePath, 'utf8')), {
        customSwaggerUiPath,
      })
      AppLogger.info('SwaggerConfig', () =>
        i18n.t('lhy-common.swagger.index.12154285-2', { args: [finalPath, jsonFilePath] })
      )
    }
  }
}
